unit StringUtils;

interface

  function WideToAnsi(const Wide : Widestring; CodePage : Cardinal) : AnsiString;
  function AnsiToWide(const Ansi : Ansistring; CodePage : Cardinal) : Widestring;
  function KoreanToUnicode(const Ansi : Ansistring) : WideString;
  function ExtractUrlFilename(const URL : Widestring) : Widestring;

implementation

  uses
    Windows, SysUtils;

  {
    WideToAnsi
      @Description
        todo
      @Parameters
        Wide = Unicode encoded string
        CodePage = Code page to be used in conversion
      @Returns
        Converted ansi string
  }
  function WideToAnsi(const Wide : WideString; CodePage : Cardinal) : AnsiString;
  var
    Length : Integer;
  begin
    if Wide = '' then
      Result := ''
    else begin
      Length := WideCharToMultiByte(
        CodePage,
        WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR,
        @Wide[1],
        -1,
        nil,
        0,
        nil,
        nil
      );
      SetLength(Result, Length - 1);
      if Length > 1 then
        WideCharToMultiByte(
          CodePage,
          WC_COMPOSITECHECK or WC_DISCARDNS or WC_SEPCHARS or WC_DEFAULTCHAR,
          @Wide[1],
          -1,
          @Result[1],
          Length - 1,
          nil,
          nil
        );
    end;
  end; { WideToAnsi }

  {
    AnsiToWide
      @Description
        todo
      @Parameters
        Ansi = Ansi string
        CodePage = String enc
      @Returns
        Converted wide string
  }
  function AnsiToWide(const Ansi : AnsiString; CodePage : Cardinal) : WideString;
  var
    Length : Integer;
  begin
    if Ansi = '' then
      Result := ''
    else begin
      Length := MultiByteToWideChar(
        CodePage,
        MB_PRECOMPOSED,
        PAnsiChar(@Ansi[1]),
        -1,
        nil,
        0
      );
      SetLength(Result, Length - 1);
      if Length > 1 then
        MultiByteToWideChar(
          CodePage,
          MB_PRECOMPOSED,
          PAnsiChar(@Ansi[1]),
          -1,
          PWideChar(@Result[1]),
          Length - 1
        );
    end;
  end; { AnsiToWide }

  {
    KoreanToUnicode
      @Description
        todo
      @Parameters
        Ansi = Ansi string
      @Result
        Korean encoded wide string
  }
  function KoreanToUnicode(const Ansi : AnsiString) : WideString;
  begin
    Result := AnsiToWide(Ansi, 51949);
  end; { KoreanToUnicode }

  {
    ExtractUrlFilename
    @Description
      todo
    @Parameters
      URL = URL containing file name
    @Result
      File name
  }
  function ExtractUrlFilename(const URL: Widestring) : Widestring;
  var
    i: Integer;
  begin
    i := LastDelimiter('/', URL);
    Result := Copy(URL, i + 1, Length(URL) - (i));
  end; { ExtractUrlFilename }

end.
